package com.itzdm.aop;

import com.alibaba.fastjson.JSONObject;
import com.itzdm.mapper.OperateLogMapper;
import com.itzdm.pojo.OperateLog;
import com.itzdm.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Component
@Aspect
@Slf4j
public class LogAspect {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private OperateLogMapper logMapper;

    @Around("@annotation(com.itzdm.anno.Log)")
    public Object record(ProceedingJoinPoint joinPoint) throws Throwable {
        String jwt = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(jwt);
        String username = (String) claims.get("username");
        LocalDateTime operateTime = LocalDateTime.now();
        String methodName = joinPoint.getSignature().getName();
        String className = joinPoint.getTarget().getClass().getName();

        Object[] args = joinPoint.getArgs();
        String methodParams = Arrays.toString(args);

        Long begin = System.currentTimeMillis();

        Object result = joinPoint.proceed();
        String returnValue = JSONObject.toJSONString(result);


        Long end = System.currentTimeMillis();

        Long time = end - begin;



        OperateLog operateLog = new OperateLog(null, username, operateTime, className, methodName, methodParams, returnValue, time);
        logMapper.insert(operateLog);
        log.info("operateLog:{}", operateLog);
        return result;
    }
}
